package com.heima.comment.service.impl;
import java.util.*;
import java.util.stream.Collectors;

import com.heima.comment.service.ApCommentRepayService;
import com.heima.comment.service.ApCommentService;
import com.heima.common.contants.RedisConstants;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.comment.dtos.ApCommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.feign.ApUserFeign;
import com.heima.utils.common.BeanHelper;
import com.heima.utils.common.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class ApCommentRepayServiceImpl implements ApCommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ApCommentService commentService;

    @Autowired
    private ApUserFeign userFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;
    //保存评论回复
    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {
        try {
            //参数校验
            if (dto == null || dto.getCommentId() == null || dto.getContent() == null){
                throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
            }

            ApUser user = (ApUser) ThreadLocalUtils.get();
            if (user == null){
                throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
            }
            ApUser apUser = userFeign.findById(user.getId()).getData();

            //内容检测
            boolean flag = commentService.handleSensitiveScan(dto.getContent());
            if (!flag){
                return ResponseResult.errorResult(400,"评论含有违规词");
            }

            ApCommentRepay commentRepay = new ApCommentRepay();

            commentRepay.setAuthorId(apUser.getId());
            commentRepay.setAuthorName(apUser.getName());
            //评论id
            commentRepay.setCommentId(dto.getCommentId());
            commentRepay.setContent(dto.getContent());
            commentRepay.setLikes(0);
            commentRepay.setCreatedTime(new Date());
            commentRepay.setUpdatedTime(new Date());

            mongoTemplate.save(commentRepay);

            //修改回复数量
            Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            ApComment comment = mongoTemplate.findOne(query, ApComment.class);
            comment.setReply(comment.getReply()+1);

            mongoTemplate.save(comment);

            return ResponseResult.okResult(null);
        } finally {
            ThreadLocalUtils.remove();
        }
    }

    //查询评论回复列表
    @Override
    public ResponseResult<List<ApCommentRepayDto>> load(CommentRepaySaveDto dto) {

        try {
            if (dto == null || dto.getMinDate() == null || dto.getCommentId() == null ){
                throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
            }

            ApUser user = (ApUser) ThreadLocalUtils.get();
            //文章评论id
            Query query =Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
            query.with(Sort.by(Sort.Direction.DESC,"createdTime"));

            List<ApCommentRepay> commentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

            List<ApCommentRepayDto> collect = new ArrayList<>();
            for (ApCommentRepay commentRepay : commentRepayList) {
                //转换对象
                ApCommentRepayDto apCommentRepayDto = BeanHelper.copyProperties(commentRepay, ApCommentRepayDto.class);
                //登录
                if (user != null){
                    //从Redis查询是否点赞
                    String key = RedisConstants.COMMENT_REPAY_LIKE + apCommentRepayDto.getId() + user.getId();
                    String commentId = redisTemplate.opsForValue().get(key);

                    if (StringUtils.isNotEmpty(commentId)){
                        //点赞
                        apCommentRepayDto.setOperation((short) 0);
                    }else {
                        apCommentRepayDto.setOperation((short) 1);
                    }
                }
                collect.add(apCommentRepayDto);
            }
            return ResponseResult.okResult(collect);
        } finally {
            ThreadLocalUtils.remove();
        }
    }

    //评论点赞 取消
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {

        try {
            //参数校验
            if (dto == null || dto.getCommentRepayId() == null){
                throw new LeadNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            //判断是否登录
            ApUser user = (ApUser) ThreadLocalUtils.get();
            if (user == null){
                throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
            }
            //判断是点赞还是取消点赞


            String key = RedisConstants.COMMENT_REPAY_LIKE + dto.getCommentRepayId() + user.getId();
            if (dto.getOperation() == 0){
                //判断是否已经点赞;
                String like = redisTemplate.opsForValue().get(key);
                if (StringUtils.isNotEmpty(like)){
                    //已经点赞
                    return ResponseResult.okResult(200,"你已经点赞，无需再点赞");
                }
                //未点赞 存入Redis 修改表中数据
                redisTemplate.opsForValue().set(key,dto.getCommentRepayId());

                Query query = Query.query(Criteria.where("_id").is(dto.getCommentRepayId()));
                ApCommentRepay commentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);

                commentRepay.setLikes(commentRepay.getLikes()+1);

                mongoTemplate.save(commentRepay);


                return ResponseResult.okResult(88);

            }else {
                //取消点赞 先查再删  从Redis删除
                //判断是否已经点赞;
                String like = redisTemplate.opsForValue().get(key);
                if (StringUtils.isEmpty(like)){
                    //没有点赞
                    return ResponseResult.okResult(200,"你未点赞，无需取消点赞");
                }

                redisTemplate.delete(key);

                Query query = Query.query(Criteria.where("_id").is(dto.getCommentRepayId()));
                ApCommentRepay commentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);

                if (commentRepay.getLikes() > 0){
                    commentRepay.setLikes(commentRepay.getLikes()-1);
                }


                mongoTemplate.save(commentRepay);


                return ResponseResult.okResult(88);
            }

        } finally {
            ThreadLocalUtils.remove();
        }
    }
}
